package com.example.spider.cluster.redis;

import org.redisson.api.RKeys;
import org.redisson.api.RedissonClient;
import org.shoulder.batch.progress.BatchProgressCache;
import org.shoulder.batch.progress.Progress;
import org.shoulder.batch.progress.ProgressAble;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于 redis 的cache
 *
 * @author lym
 */
public class RedisBatchProgressCache implements BatchProgressCache {

    final RedissonClient redissonClient;

    public RedisBatchProgressCache(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public Progress getProgress(String id) {
        return RedisFixedNumProgress.of(id, redissonClient);
    }

    @Override
    public Iterable<String> getAllTaskProgressId() {
        return redissonClient.getKeys().getKeysByPattern(RedisFixedNumProgress.CACHE_KEY_PREFIX + "*");
    }

    @Override
    public Map<String, Progress> getAllTaskProgress() {
        Map<String, Progress> result = new HashMap<>();
        getAllTaskProgressId().forEach(k -> {
            result.put(k, RedisFixedNumProgress.of(k, redissonClient));
        });
        return result;
    }

    @Override
    public void flushProgress(ProgressAble batchProgress) {
        checkSupport(batchProgress);
    }

    @Override
    public void triggerFlushProgress(ProgressAble batchProgress) {
        checkSupport(batchProgress);
    }

    @Override
    public void evict(String id) {
        RKeys redis = redissonClient.getKeys();
        redis.deleteByPatternAsync(RedisFixedNumProgress.CACHE_KEY_PREFIX + id + "*");
    }

    @Override
    public void clear() {
        RKeys redis = redissonClient.getKeys();
        redis.deleteByPatternAsync(RedisFixedNumProgress.CACHE_KEY_PREFIX + "*");
    }

    public static void checkSupport(ProgressAble batchProgress) {
        if (batchProgress == null || batchProgress.getClass() != RedisFixedNumProgress.class) {
            throw new IllegalArgumentException("onlu support RedisFixedNumProgress");
        }
    }

}